package com.loveprogrammer.utils;

import com.loveprogrammer.engine.enums.QualityEnum;
import com.loveprogrammer.factory.MonsterFactory;
import com.loveprogrammer.model.Monster;
import com.loveprogrammer.model.battle.MonsterInMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @version 1.0.0
 * @description: 随机工具类
 * @author: eric
 * @date: 2022-08-03 18:30
 **/
public class RandomBalance {

    private static final Random RANDOM = new Random();
    private static Integer weightSum = 0;

    public static <T> T findByPercents(Map<T,Integer> feeds){
        // 先求和
        int total = 0;
        T key = null;
        for (Map.Entry<T, Integer> entry : feeds.entrySet()) {
            total += entry.getValue();
        }
        int factor = new Random().nextInt(total);
        int count = 0;
        for (Map.Entry<T, Integer> entry : feeds.entrySet()) {
            if((entry.getValue()+count) > factor){
                key = entry.getKey();
                break;
            }
            count += entry.getValue();
        }

        return key;
    }

    public static Monster getMonsters(List<MonsterInMap> monsters) {
        if (monsters == null){
            return null;
        }
        int tempWeightSum = 0;
        List<MonsterInMap> list = new ArrayList<>();
        for (MonsterInMap server : monsters) {
            int weight = server.getPercents();
            tempWeightSum += weight;
            for (int i = 0; i < weight; i++) {
                list.add(server);
            }
        }
        weightSum = tempWeightSum;
        System.out.println("list size = " + list.size() + ",weightSum = " + weightSum);
        MonsterInMap monsterInMap = list.get(RANDOM.nextInt(weightSum));
        int level;
        if(monsterInMap.getLevelMax() == monsterInMap.getLevelMin()){
            level = monsterInMap.getLevelMin();
        }else {
            level = monsterInMap.getLevelMin() + new Random().nextInt(monsterInMap.getLevelMax() - monsterInMap.getLevelMin());
        }
        int monsterId = monsterInMap.getMonsterTemplate().getId();

        return MonsterFactory.createMonster(monsterId,level);

    }


    public static QualityEnum findQuality(int white, int blue, int yellow, int purple, int red, int gold, int green) {
        int sum = white + blue + yellow + purple + red + gold + green;
        int index = new Random().nextInt(sum);
        if(white > index)
            return QualityEnum.白色;
        if((white + blue) > index)
            return QualityEnum.蓝色;
        if((white + blue + yellow) > index)
            return QualityEnum.黄色;
        if((white + blue + yellow + purple) > index)
            return QualityEnum.紫色;
        if((white + blue + yellow + purple + red) > index)
            return QualityEnum.红色;
        if((white + blue + yellow + purple + red + gold) > index)
            return QualityEnum.暗金;

        return QualityEnum.绿色;

    }
}
